package com.ruicar.afs.cloud.apply.archive.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.ruicar.afs.cloud.apply.archive.condition.ArchivedDataCondition;
import com.ruicar.afs.cloud.apply.archive.enums.ApplyMappingArchiveEnum;
import com.ruicar.afs.cloud.apply.archive.enums.ArchiveEnum;
import com.ruicar.afs.cloud.apply.archive.service.ApplyMappingArchiveService;
import com.ruicar.afs.cloud.apply.archive.vo.*;
import com.ruicar.afs.cloud.apply.business.service.ApplySignRelationService;
import com.ruicar.afs.cloud.apply.channel.condition.AffiliationCondition;
import com.ruicar.afs.cloud.apply.common.dto.ChannelAffiliatedUnitsDto;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.feign.Apply2ChannelFeign;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConfig;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.common.utils.ApplyUtils;
import com.ruicar.afs.cloud.apply.contract.service.ApplyBankCardService;
import com.ruicar.afs.cloud.apply.contract.service.ApplyContractInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.archive.utils.ArchiveConstants;
import com.ruicar.afs.cloud.bizcommon.algorithm.enums.CalculateType;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.CustRoleEnum;
import com.ruicar.afs.cloud.common.modules.apply.enums.CarTypeEnum;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.entity.ComAttachmentManagement;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.image.service.ComAttachmentManagementService;
import com.ruicar.afs.cloud.parameter.commom.enums.WhetherEnum;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * @ClassName ArchivedDataController
 * @Description: 同步归档数据给CMS系统
 * @Author zyr
 * @Date 2020/8/22
 * @Version V1.0
 **/
@AllArgsConstructor
@RestController
@RequestMapping("/archivedData")
public class ArchivedDataController {

    private static final Logger logger = LoggerFactory.getLogger(ArchivedDataController.class);

    private final ComAttachmentFileService comAttachmentFileService;
    private final ApplyContractInfoService applyContractInfoService;
    private final ApplyChannelInfoService applyChannelInfoService;
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ApplyCarDetailsService applyCarDetailsService;
    private final ApplyCostDetailsService applyCostDetailsService;
    private final ApplyOrderInfoService applyOrderInfoService;
    private final ApplyAffiliatedUnitService applyAffiliatedUnitService;
    private final ApplySignRelationService applySignRelationService;
    private final ComAttachmentManagementService comAttachmentManagementService;
    private final Apply2ChannelFeign apply2ChannelFeign;
    private final ApplyConfig config;
    private final ApplyBankCardService applyBankCardService;
    private final ApplyMappingArchiveService applyMappingArchiveService;

    /**
     * 获取归档数据
     * @param condition
     * @return
     */
    @ApiOperation("获取归档数据")
    @PostMapping("/getArchivedData")
    public JSONObject getArchivedData(@RequestBody ArchivedDataCondition condition) {

        //申请编号
        String applicationNo = condition.getApplicationNo();
        if(StringUtils.isBlank(applicationNo)){
            return this.result(0,null,"申请编号不能为空","申请编号不能为空");
        }
        try{
            //总结果
            ArchivedResultVo archivedResultVo = new ArchivedResultVo();
            //申请信息
            ArchivedCamainVo archivedCamainVo = new ArchivedCamainVo();
            //电子签信息
            ArchivedCasignVo archivedCasignVo = new ArchivedCasignVo();
            //业务类型
            ArchivedCacategoryVo archivedCacategoryVo = new ArchivedCacategoryVo();
            //合同信息
            ArchivedCacontractVo archivedCacontractVo = new ArchivedCacontractVo();
            //业务类型附属信息
            ArchivedCaanchoredinfoVo archivedCaanchoredinfoVo = new ArchivedCaanchoredinfoVo();

            //订单申请表
            ApplyOrderInfo applyOrderInfo = applyOrderInfoService.getOne(Wrappers.<ApplyOrderInfo>query().lambda()
                            .eq(ApplyOrderInfo::getApplyNo, applicationNo)
                    ,false
            );
            //银行卡申请表
            ApplyBankCard applyBankCard = applyBankCardService.getOne(Wrappers.<ApplyBankCard>query().lambda()
                            .eq(ApplyBankCard::getApplyNo, applicationNo)
                    ,false
            );
            //车辆申请表
            ApplyCarDetails applyCarDetails = applyCarDetailsService.getOne(Wrappers.<ApplyCarDetails>query().lambda()
                            .eq(ApplyCarDetails::getApplyNo, applicationNo)
                    ,false
            );
            //渠道申请表
            ApplyChannelInfo applyChannelInfo = applyChannelInfoService.getOne(Wrappers.<ApplyChannelInfo>query().lambda()
                            .eq(ApplyChannelInfo::getApplyNo, applicationNo)
                    ,false
            );
            //合同信息
            ApplyContractInfo applyContractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda()
                            .eq(ApplyContractInfo::getApplyNo, applicationNo)
                    ,false
            );
            //融资费用申请表
            FinCostDetails finCostDetails = applyCostDetailsService.getOne(Wrappers.<FinCostDetails>query().lambda()
                            .eq(FinCostDetails::getApplyNo, applicationNo)
                            .eq(FinCostDetails::getCostType, ApplyConstants.COST_TYPE_CAR_LOAN)
                    ,false
            );
            //融资费用申请表
            List<FinCostDetails> finCostDetailsList = applyCostDetailsService.list(Wrappers.<FinCostDetails>query().lambda()
                    .eq(FinCostDetails::getApplyNo, applicationNo)
            );
            //客户申请主表-主借人
            ApplyCustBaseInfo applyCustBaseInfoM = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                            .eq(ApplyCustBaseInfo::getApplyNo,applicationNo)
                            .eq(ApplyCustBaseInfo::getCustRole,  AfsEnumUtil.key(CustRoleEnum.MIANCUST))
                    ,false
            );
            //客户申请主表-主借人
            ApplyCustBaseInfo applyCustBaseInfoC = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                            .eq(ApplyCustBaseInfo::getApplyNo, applicationNo)
                            .eq(ApplyCustBaseInfo::getCustRole,  AfsEnumUtil.key(CustRoleEnum.COMMONCSUT))
                    ,false
            );
            //挂靠单位申请表
            ApplyAffiliatedUnit applyAffiliatedUnit = applyAffiliatedUnitService.getOne(Wrappers.<ApplyAffiliatedUnit>query().lambda()
                            .eq(ApplyAffiliatedUnit::getApplyNo, applicationNo)
                    ,false
            );


            //车辆类型====>车辆属性
            archivedCacategoryVo.setVehicletype(applyMappingArchiveService.queryMappingResult(
                    ApplyMappingArchiveEnum.vehicletype,
                    applyOrderInfo.getCarNature())
            );

            //业务类型======》业务类型、车辆类型、运营方式、挂靠方式
            archivedCacategoryVo.setBusinesstype(applyMappingArchiveService.queryMappingResult(
                    ApplyMappingArchiveEnum.businesstype,
                    applyOrderInfo.getBusinessType(),
                    applyOrderInfo.getCarType(),
                    applyOrderInfo.getOperateWay(),
                    applyOrderInfo.getAffiliatedWay())
            );
            archivedCamainVo.setId(applyOrderInfo.getId().toString());//申请ID
            //提交时间为空时，默认撤销
            archivedCamainVo.setSubmitdate(applyOrderInfo.getIntoFirstDate()!=null?DateUtil.formatDateTime(applyOrderInfo.getIntoFirstDate())
                    :DateUtil.formatDateTime(applyOrderInfo.getCancelDate()));//申请提交时间
            archivedCacontractVo.setSpedate(applyOrderInfo.getRiskPassDate()!=null?DateUtil.formatDateTime(applyOrderInfo.getRiskPassDate())
                    :DateUtil.formatDateTime(applyOrderInfo.getCancelDate()));//案件审批时间

            archivedCacontractVo.setBorrowername(applyOrderInfo.getCustName());//客户姓名
            archivedCacontractVo.setPurpose(ArchiveConstants.PURPOSE.get(applyOrderInfo.getCarPurpose()));//购车目的
            archivedCasignVo.setStatus("1".equals(applyOrderInfo.getSignFlag())?2:0);//申请签署状态(总)


            if(applyBankCard!=null){
                archivedCacontractVo.setPaymentbank(applyBankCard.getBankCode());//银行code
            }
            archivedCacontractVo.setVin(applyCarDetails.getCarVin());//VIN号
            archivedCacontractVo.setEngineno(applyCarDetails.getEngineNo());//发动机号
            archivedCacontractVo.setVehicleinfo(applyCarDetails.getBrandName());//车辆品牌
            archivedCacontractVo.setArea(applyCarDetails.getLicenseCity());//省市
            archivedCacontractVo.setSigndealer(applyChannelInfo.getChannelId());//签约经销商

            //案件类别======》业务类型
            archivedCacontractVo.setCategory(Integer.parseInt(applyMappingArchiveService.queryMappingResult(
                    ApplyMappingArchiveEnum.category,
                    applyOrderInfo.getBusinessType()))
            );
            archivedCacontractVo.setCamainno(applicationNo);//申请编号

            //判断
            String isLending = "1";

            if(applyContractInfo!=null){
                archivedCacontractVo.setCacontractId(applyContractInfo.getId().toString());//默认申请ID
                archivedCacontractVo.setActivedate(DateUtil.formatDateTime(applyContractInfo.getStartDate()));//激活时间
                //流程结束时间
                archivedCacontractVo.setWfedate(applyContractInfo.getLendingPassDate()!=null?
                        DateUtil.formatDateTime(applyContractInfo.getLendingPassDate()) : DateUtil.formatDateTime(applyContractInfo.getCancelDate())
                );
                archivedCacontractVo.setContractno(applyContractInfo.getContractNo());//合同编号
                archivedCasignVo.setCstatus("1".equals(applyContractInfo.getSignFlag())?2:0);//合同签署状态(总)
                archivedCacontractVo.setEdate(DateUtil.formatDateTime(applyContractInfo.getEndDate()));//合同到期日期

                //是否放款判断

                if(applyContractInfo.getLendingFirstDate()!=null){
                    isLending = "3";
                }else{
                    isLending = "2";
                }

                //合同状态
                archivedCacontractVo.setStatus(Integer.parseInt(
                        applyMappingArchiveService.queryMappingResult(
                                ApplyMappingArchiveEnum.status,
                                isLending,
                                applyOrderInfo.getApplyStatus(),
                                applyContractInfo.getContractStatus()
                        )
                ));
                //案件状态(内)
                archivedCacontractVo.setStatusex(Integer.parseInt(
                        applyMappingArchiveService.queryMappingResult(
                                ApplyMappingArchiveEnum.statusex,
                                isLending,
                                applyOrderInfo.getApplyStatus(),
                                applyContractInfo.getContractStatus()
                        )
                ));
                //审批状态
                archivedCacontractVo.setSigned(Integer.parseInt(
                        applyMappingArchiveService.queryMappingResult(
                                ApplyMappingArchiveEnum.signed,
                                isLending,
                                applyOrderInfo.getApplyStatus(),
                                applyContractInfo.getContractStatus()
                        )
                ));
                //申请审批状态
                archivedCamainVo.setMstatus(Integer.parseInt(
                        applyMappingArchiveService.queryMappingResult(
                                ApplyMappingArchiveEnum.mstatus,
                                isLending,
                                applyOrderInfo.getApplyStatus(),
                                applyContractInfo.getContractStatus()
                        )
                ));
                //归档类型
                archivedCacontractVo.setFiletype(Integer.parseInt(
                        applyMappingArchiveService.queryMappingResult(
                                ApplyMappingArchiveEnum.filetype,
                                isLending,
                                applyOrderInfo.getApplyStatus(),
                                applyContractInfo.getContractStatus()
                        )
                ));

            }else{
                archivedCacontractVo.setCacontractId(applyOrderInfo.getId().toString());//默认申请ID

                //合同状态
                archivedCacontractVo.setStatus(Integer.parseInt(
                        applyMappingArchiveService.queryMappingResult(
                                ApplyMappingArchiveEnum.status,
                                isLending,
                                applyOrderInfo.getApplyStatus()
                        )
                ));
                //案件状态(内)
                archivedCacontractVo.setStatusex(Integer.parseInt(
                        applyMappingArchiveService.queryMappingResult(
                                ApplyMappingArchiveEnum.statusex,
                                isLending,
                                applyOrderInfo.getApplyStatus()
                        )
                ));
                //审批状态
                archivedCacontractVo.setSigned(Integer.parseInt(
                        applyMappingArchiveService.queryMappingResult(
                                ApplyMappingArchiveEnum.signed,
                                isLending,
                                applyOrderInfo.getApplyStatus()
                        )
                ));
                //申请审批状态
                archivedCamainVo.setMstatus(Integer.parseInt(
                        applyMappingArchiveService.queryMappingResult(
                                ApplyMappingArchiveEnum.mstatus,
                                isLending,
                                applyOrderInfo.getApplyStatus()
                        )
                ));
                //归档类型
                archivedCacontractVo.setFiletype(Integer.parseInt(
                        applyMappingArchiveService.queryMappingResult(
                                ApplyMappingArchiveEnum.filetype,
                                isLending,
                                applyOrderInfo.getApplyStatus()

                        )
                ));
            }


            BigDecimal loanmoney = BigDecimal.ZERO;
            BigDecimal allmoney = BigDecimal.ZERO;
            for(FinCostDetails finCostDetails1 : finCostDetailsList){
                loanmoney = loanmoney.add(finCostDetails1.getLoanAmt());
                allmoney = allmoney.add(finCostDetails1.getContractAmt());
            }
            archivedCacontractVo.setLoanmoney(loanmoney);//贷款金额
            archivedCacontractVo.setAllmoney(allmoney);//资产金额
            archivedCacontractVo.setFnproduct(finCostDetails.getProductName());//金融产品
            archivedCacontractVo.setLoanperiod(finCostDetails.getLoanTerm());//期数
            archivedCacontractVo.setCardtype(ArchiveConstants.CARDTYPE.get(applyCustBaseInfoM.getCertType()));//证件类型
            archivedCacontractVo.setCard(applyCustBaseInfoM.getCertNo());//身份证号

            if(!CalculateType.structuredloan.getValue().equals(finCostDetails.getAlgorithmType())){ //融资费用申请表-算法类型
                archivedCamainVo.setRatecaltype(0);//结构化还款
            }
            if(applyCustBaseInfoC!=null){//客户申请主表-主借人信息
                archivedCamainVo.setColoan(applyCustBaseInfoC.getCustName());//共借人
            }

            //挂靠信息补全
            archivedCaanchoredinfoVo.setAnchoredtype(ArchiveConstants.ANCHOREDTYPE.get(applyOrderInfo.getAffiliatedWay()));//挂靠方式
            if(applyAffiliatedUnit!=null){
                archivedCaanchoredinfoVo.setLicense(applyAffiliatedUnit.getSocUniCrtCode());//统一社会信用代码
                archivedCaanchoredinfoVo.setRegisteredaddress(applyAffiliatedUnit.getRegistAddress());//注册地址
                archivedCaanchoredinfoVo.setLegalperson(applyAffiliatedUnit.getLegalName());//法人姓名
                archivedCaanchoredinfoVo.setPhone(applyAffiliatedUnit.getLegalPhone());//联系电话
                archivedCaanchoredinfoVo.setTranspotrlimite(DateUtil.formatDateTime(applyAffiliatedUnit.getLicenceEndDate()));//道路运输许可证有效期
                archivedCaanchoredinfoVo.setCity(applyAffiliatedUnit.getRegistCity());//省市
                archivedCaanchoredinfoVo.setNetworkvehicletype(ArchiveConstants.NETWORKVEHICLETYPE.get(applyAffiliatedUnit.getPlatformId()));//网约车平台类型
                if(applyOrderInfo.getAffiliatedWay().equals("02")){//2
                    archivedCaanchoredinfoVo.setIndividualbusiness(applyAffiliatedUnit.getAffiliatedName());//个体工商户名称
                }else if(applyOrderInfo.getAffiliatedWay().equals("01")){//3
                    archivedCaanchoredinfoVo.setCompany(applyAffiliatedUnit.getAffiliatedName());//公司名称
                }else if(applyOrderInfo.getAffiliatedWay().equals("03")){//4
                    archivedCaanchoredinfoVo.setCompany(applyAffiliatedUnit.getAffiliatedName());//公司名称
                    archivedCaanchoredinfoVo.setNetworkvehicle(applyAffiliatedUnit.getAffiliatedId());//网约车运营公司id
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("id",applyAffiliatedUnit.getAffiliatedId().toString());
                    ChannelAffiliatedUnitsDto channelAffiliatedUnitsDto =  this.getAffiliatedById(json);
                    archivedCaanchoredinfoVo.setLegalcard(channelAffiliatedUnitsDto.getLegalPersonIdcard());//法人身份证号
                    archivedCaanchoredinfoVo.setRegisterdecapital(channelAffiliatedUnitsDto.getRegisteredCapital());//注册资本
                    archivedCaanchoredinfoVo.setRegisteredtime(DateUtil.formatDateTime(channelAffiliatedUnitsDto.getRegisteredTime()));//注册时间
                }catch (Exception e){
                    logger.info("获取挂靠信息失败："+e);
                }
            }
            //最终数据汇总
            archivedResultVo.setDataId(archivedCacontractVo.getCacontractId());//合同ID
            archivedResultVo.setCamain(archivedCamainVo);//申请信息
            archivedResultVo.setCacontract(archivedCacontractVo);//合同信息
            archivedResultVo.setCacategory(archivedCacategoryVo);//业务类型
            archivedResultVo.setCaanchoredinfo(archivedCaanchoredinfoVo);//业务类型附属信息
            archivedResultVo.setCasign(archivedCasignVo);//电子签

            return this.result(1,JSON.parseObject(JSON.toJSONString(archivedResultVo)),null,null);
        }catch (Exception e){
            return this.result(0,null,e.toString(),e.toString());
        }
    }

    /**
     * 获取电子签数据
     * @param condition
     * @return
     */
    @ApiOperation("获取电子签数据")
    @PostMapping("/getElectronicVisa")
    public JSONObject getElectronicVisa(@RequestBody ArchivedDataCondition condition) {
        try {
            //返回结果
            List result = new ArrayList();
            //申请号查询附件
            List<String> archiveClassListByAppNo = Arrays.asList(
                    AfsEnumUtil.key(ArchiveEnum.FILECATEGORY_1001),
                    AfsEnumUtil.key(ArchiveEnum.FILECATEGORY_1002)
            );
            result = this.getResult(result,condition.getApplicationNo(),archiveClassListByAppNo,ArchiveConstants.CACATEGORY_CAMAIN);

            //合同信息
            ApplyContractInfo applyContractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda()
                            .eq(ApplyContractInfo::getApplyNo, condition.getApplicationNo())
                    ,false
            );
            if( applyContractInfo!=null && applyContractInfo.getLendingFirstDate()!=null){
                //合同号查询附件
                List<String> archiveClassListByContractNo = Arrays.asList(
                        AfsEnumUtil.key(ArchiveEnum.FILECATEGORY_2001),
                        AfsEnumUtil.key(ArchiveEnum.FILECATEGORY_2002),
                        AfsEnumUtil.key(ArchiveEnum.FILECATEGORY_2003),
                        AfsEnumUtil.key(ArchiveEnum.FILECATEGORY_2004),
                        AfsEnumUtil.key(ArchiveEnum.FILECATEGORY_2005),
                        AfsEnumUtil.key(ArchiveEnum.FILECATEGORY_2006)
                );
                result = this.getResult(result,condition.getContractNo(),archiveClassListByContractNo,ArchiveConstants.CACATEGORY_CONTRACT);
            }
            //最终返回数据组装
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success",1);
            jsonObject.put("data",result);
            return jsonObject;
        }catch (Exception e){
            return this.result(0,null,e.toString(),e.toString());
        }
    }

    /**
     * @param result 结果
     * @param queryNo 业务编号
     * @param archiveClassList 归档附件类型
     * @param cacategory 阶段类型
     * @return
     */
    public List getResult(List result,String busiNo,List<String> archiveClassList,String cacategory){
        for(String archiveClass : archiveClassList){
            //根据编号以及附件类型查询附件信息
            ComAttachmentFile comAttachmentFile = comAttachmentFileService.getOne(Wrappers.<ComAttachmentFile>query().lambda()
                    .eq(ComAttachmentFile::getBusiNo, busiNo)
                    .eq(ComAttachmentFile::getIsElectronic, WhetherEnum.YES.getIndex())
                    .eq(ComAttachmentFile::getArchiveClass,archiveClass)
                    .orderByDesc(ComAttachmentFile::getCreateTime)
                    ,false
            );
            if(comAttachmentFile!=null){
                //查询合同签约关系表
                List<ApplySignRelation> applySignRelations = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                        .eq(ApplySignRelation::getBusinessNo,busiNo)
                        .eq(ApplySignRelation::getTempleId,comAttachmentFile.getAttachmentCode())
                );
                String partytype = "";//申请人类型
                String partytypename = "";//申请人类型(中文)
                for(ApplySignRelation applySignRelation:applySignRelations){
                    partytype += ArchiveConstants.PARTYTYPE.get(applySignRelation.getCustRole())+",";
                    partytypename +=  ApplyUtils.dicData(applySignRelation.getCustRole(),AfsEnumUtil.key(ArchiveEnum.PARTYTYPENAME));//申请人类型(中文)
                }
                JSONObject json = new JSONObject();
                json.put("filecategory",comAttachmentFile.getArchiveClass());//文件类别
                json.put("filecategoryname",ApplyUtils.dicData(comAttachmentFile.getArchiveClass(), AfsEnumUtil.key(ArchiveEnum.FILECATEGORYNAME)));//文件类别(中文)
                json.put("partytype",partytype);//申请人类型
                json.put("partytypename",partytypename);//申请人类型(中文)
                json.put("signedappfilemd5",comAttachmentFile.getFileId());//签署后的申请文件md5
                json.put("cacategory",cacategory);//阶段类型
                result.add(json);
            }
        }
        return result;
    }


    /**
     * 归档反馈
     * @param condition
     * @return
     */
    @ApiOperation("归档反馈")
    @PostMapping("/archiveFeedback")
    public JSONObject archiveFeedback(@RequestBody ArchivedDataCondition condition) {
        return this.result(1,null,null,null);
    }

    /**
     * 获取银行卡身份证影像件
     * @param condition
     * @return
     */
    @ApiOperation("获取银行卡身份证影像件")
    @PostMapping("/getCardImage")
    public JSONObject getCardImage(@RequestBody ArchivedDataCondition condition) {
        try {
            //附件小类唯一编码
            List<String> uniqueCodeList = Arrays.asList("repayIdCardFront","repayIdCardBack","repayBankCardFront","repayBankCardBack");
            //查询影像
            List<ComAttachmentManagement> comAttachmentManagements = comAttachmentManagementService.list(Wrappers.<ComAttachmentManagement>query().lambda()
                    .eq(ComAttachmentManagement::getBusiNode,"loanApply")
                    .in(ComAttachmentManagement::getUniqueCode,uniqueCodeList)
            );
            //附件编号
            List<String> attachmentCodeList = Lists.transform(comAttachmentManagements, (comAttachmentManagement) -> {
                return comAttachmentManagement.getId().toString();
            });
            //查询影像文件
            List<ComAttachmentFile> comAttachmentFiles = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                    .in(ComAttachmentFile::getAttachmentCode, attachmentCodeList)
                    .eq(ComAttachmentFile::getBusiNo, condition.getContractNo())
            );
            //返回结果
            List result = new ArrayList();
            for(ComAttachmentFile comAttachmentFile : comAttachmentFiles){
                JSONObject json = new JSONObject();
                json.put("imcategoryCode",comAttachmentFile.getArchiveClass());//文件类别
                json.put("imcategoryName",ApplyUtils.dicData(comAttachmentFile.getArchiveClass(), AfsEnumUtil.key(ArchiveEnum.FILECATEGORYNAME)));//文件类别(中文)
                json.put("md5",comAttachmentFile.getFileId());//签署后的申请文件md5
                result.add(json);
            }
            //最终返回数据组装
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success",1);
            jsonObject.put("data",result);
            return jsonObject;
        }catch (Exception e){
            return this.result(0,null,e.toString(),e.toString());
        }
    }

    /**
     * 调用返回
     * @param success
     * @param data
     * @param message
     * @param code
     * @return
     */
    public JSONObject result(Integer success,JSONObject data,String message,String code) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success",success);
        //成功
        if(1==success){
            jsonObject.put("data",data);
        }else{//失败
            jsonObject.put("message",message);
            jsonObject.put("code",code);
        }
        return jsonObject;
    }

    /**
     * 根据挂靠ID查询挂靠信息
     * @param condition
     * @return
     */
    public ChannelAffiliatedUnitsDto getAffiliatedById(JSONObject condition) {
        //截取字符串
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", config.getCaseClientId());
        headers.put("clientSecret", config.getCaseClientSecret());
        return apply2ChannelFeign.getAffiliatedById(condition, headers);
    }

}
